/*
 * MIT License
 *
 * Copyright (c) 2020 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package cn.seaboot.openapi;

import cn.seaboot.commons.core.CommonUtils;
import cn.seaboot.openapi.base.ControllerInfo;
import cn.seaboot.openapi.item.DefaultItemAnalyzer;
import cn.seaboot.openapi.item.ItemAnalyzer;
import cn.seaboot.postman.root.Info;
import cn.seaboot.postman.root.Item;
import cn.seaboot.postman.root.Postman;
import cn.seaboot.postman.root.Variable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

/**
 * 采用 fluent 写法的 Postman 构建工具
 *
 * @author Mr.css
 * @version 2020-01-28 11:46
 */
public class PostmanBuilder {
    private final Logger logger = LoggerFactory.getLogger(PostmanBuilder.class);
    private final Postman postman = new Postman();
    private final Set<Item> items = new TreeSet<>();

    /**
     * 后台运行环境
     */
    private Environment environment = new Environment();

    /**
     * 接口扫描器
     */
    private ItemAnalyzer itemAnalyzer = new DefaultItemAnalyzer(this);

    /**
     * 建造者模式
     *
     * @return this；
     */
    public static PostmanBuilder create() {
        return new PostmanBuilder();
    }

    private PostmanBuilder() {
    }

    /**
     * search api by ApplicationContext
     *
     * @param context ApplicationContext
     * @return PostmanBuilder
     */
    public PostmanBuilder searchContext(ApplicationContext context) {
        //扫描所有的Controller
        Map<String, Object> controllers = context.getBeansWithAnnotation(Controller.class);
        if (CommonUtils.isNotEmpty(controllers)) {
            for (Object controller : controllers.values()) {
                this.searchApi(controller.getClass());
            }
        }
        //扫描所有的RestController
        controllers = context.getBeansWithAnnotation(RestController.class);
        if (CommonUtils.isNotEmpty(controllers)) {
            for (Object controller : controllers.values()) {
                this.searchApi(controller.getClass());
            }
        }
        return this;
    }


    /**
     * 扫描接口
     * <p>
     * Get api form a controller.
     * A Controller can get one or more api-group, because a Controller can map to any url.
     * If the number of {@link RequestMapping#value()} is bigger than 1, will get more api-group.
     * The number {@link RequestMapping#value()} is the same as number of api-group.
     *
     * @param clazz controller' Class
     * @return List<Item>
     */
    public PostmanBuilder searchApi(Class<?> clazz) {
        if (this.supports(clazz)) {
            RequestMapping requestMapping = clazz.getDeclaredAnnotation(RequestMapping.class);
            if (requestMapping != null) {
                logger.debug("OpenAPI start search API：" + clazz);
                ControllerInfo controllerInfo = new ControllerInfo(clazz, requestMapping);
                if (!controllerInfo.getMethodInfos().isEmpty()) {
                    items.addAll(itemAnalyzer.analyze(controllerInfo));
                }
            }
        }
        return this;
    }

    /**
     * 白名单，接受此类的 Class，优先检测白名单
     */
    private String[] include;
    /**
     * 黑名单，拒绝此类的 Class
     */
    private String[] exclusive;
    /**
     * 路径匹配校验
     */
    private final AntPathMatcher matcher = new AntPathMatcher(".");

    /**
     * 决定是否处理当前类
     */
    public boolean supports(Class<?> clazz) {
        String className = clazz.getName();
        if (CommonUtils.isNotEmpty(include)) {
            for (String str : include) {
                if (matcher.match(str, className)) {
                    return true;
                }
            }
        }
        if (CommonUtils.isNotEmpty(exclusive)) {
            for (String str : exclusive) {
                if (className.startsWith(str) || matcher.match(str, className)) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * return Postman node
     *
     * @return Postman
     */
    public Postman build() {
        // API 基本信息
        Info info = new Info();
        info.set_postman_id(environment.getPostmanId());
        info.setName(environment.getName());
        info.setSchema(environment.getPostmanVersion());
        this.postman.setInfo(info);

        // API 共享变量
        Variable[] variables = environment.getVariables();
        if(CommonUtils.isEmpty(variables)){
            variables = environment.defaultVariable();
        }
        this.postman.setVariable(variables);

        this.postman.setItem(items.toArray(new Item[]{}));
        return this.postman;
    }

    //getter/setter---------------------------------------------------

    public PostmanBuilder setVariable(Variable variable) {
        postman.setVariable(new Variable[]{variable});
        return this;
    }

    public PostmanBuilder setInfo(Info info) {
        postman.setInfo(info);
        return this;
    }

    public PostmanBuilder addItem(List<Item> item) {
        items.addAll(item);
        return this;
    }

    public PostmanBuilder setItemAnalyzer(ItemAnalyzer itemAnalyzer) {
        this.itemAnalyzer = itemAnalyzer;
        return this;
    }

    public PostmanBuilder setEnvironment(Environment environment) {
        this.environment = environment;
        return this;
    }

    public PostmanBuilder setInclude(String include) {
        this.include = include.split(";");
        return this;
    }

    public PostmanBuilder setExclusive(String exclusive) {
        this.exclusive = exclusive.split(";");
        return this;
    }

    public Set<Item> getItems() {
        return items;
    }

    public Environment getEnvironment() {
        return environment;
    }

    public ItemAnalyzer getItemAnalyzer() {
        return itemAnalyzer;
    }

    public String[] getInclude() {
        return include;
    }

    public String[] getExclusive() {
        return exclusive;
    }
}
